package com.czl.common.auth;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.czl.common.redisbase.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

@Component
public class CommonSessionRedis implements Serializable {

	private static final Logger LOGGER = LoggerFactory.getLogger(CommonSessionRedis.class);

	private static final long serialVersionUID = 1921149354182034151L;
	@Autowired
	private RedisUtils redisUtilBean;


	static RedisUtils redisUtils;

	@PostConstruct
	private void init() {
		CommonSessionRedis.redisUtils = redisUtilBean;
	}

	private HttpServletRequest request;

	private CommonLoginInfo loginInfo;

	private Map<String,Object> threadData;


	@Deprecated
	public Long getUid() {

		if(loginInfo == null){
			return null;
		}

		return loginInfo.getUid();
	}

	public Long getOriginalUid() {

		if(loginInfo == null){
			return null;
		}

		return loginInfo.getUid();
	}

	public String getCompleteUid() {

		if(loginInfo == null){
			return null;
		}

		return loginInfo.appTag+loginInfo.getUid();
	}
	
	public HttpServletRequest getRequest() {
		return this.request;
	}

	public CommonLoginInfo getLoginInfo() {
		return this.loginInfo;
	}

	public void setLoginInfo(final CommonLoginInfo loginInfo) {
		this.loginInfo = loginInfo;
	}

	public void addToThreadData(String key, Object value) {
		this.threadData.put(key, value);
	}

	public Object getThreadData(String key) {
		return this.threadData.get(key);
	}
	
	public void destroy() {
		
	}

	public static CommonSessionRedis getInstance(HttpServletRequest request){
		String sessionId = request.getHeader("gateway_session_id");
		if(redisUtils==null){
			redisUtils = SpringUtil.getBean(RedisUtils.class);
		}
		Object o = redisUtils.get(sessionId);
		String jsonStr = JSONUtil.toJsonStr(o);
		LOGGER.info("jsonStr========:"+jsonStr);
		CommonSessionRedis commonSessionRedis = JSONUtil.toBean(jsonStr, CommonSessionRedis.class);
		return commonSessionRedis;
	}

	public static CommonSessionRedis getInstance(String sessionId){
		if(redisUtils==null){
			redisUtils = SpringUtil.getBean(RedisUtils.class);
		}
		Object o = redisUtils.get(sessionId);
		String jsonStr = JSONUtil.toJsonStr(o);
		LOGGER.info("CommonSessionRedis.getInstance,{},{}",sessionId,jsonStr);
		CommonSessionRedis commonSessionRedis = JSONUtil.toBean(jsonStr, CommonSessionRedis.class);
        LOGGER.info("CommonSessionRedis.commonSessionRedis,{},{}",sessionId,jsonStr,JSONUtil.toJsonStr(commonSessionRedis));
		return commonSessionRedis;
	}

	public void init(String sessionId){
		if(redisUtils==null){
			redisUtils = SpringUtil.getBean(RedisUtils.class);
		}
		redisUtils.set(sessionId,this);
	}

}
